#include "stm32f10x.h"                  // Device header
#include "MyI2C.h"
#include "MPU6050Reg.h"

#define MPU6050_Address 0xD0

uint8_t MPU6050_ReceiveData[100] = { 0 };
uint8_t MPU6050_WriteData[100] = { 0 };
int16_t MPU6050_Stateinfo[7] = { 0 };           //前3为存储Ax Ay Az 第4位'C 第五位Gx Gy Gz



//指定地址写入 一个字节
void MPU6050_WriteReg_Single(uint8_t RegAddress, uint8_t Data)
{
    MyI2C_Start();
	MyI2C_SetAddress_R_W(MPU6050_Address, Write);
	MyI2C_ReceiveAck();
	MyI2C_SetRegAddress(RegAddress);
	MyI2C_ReceiveAck();
    MyI2C_SendByte(Data);
    MyI2C_ReceiveAck();
    MyI2C_Stop();
}

//指定地址写入 一组数据
void MPU6050_WriteReg_Multiply(uint8_t RegAddress, uint8_t *Data, uint16_t Count)
{
    MyI2C_Start();
	MyI2C_SetAddress_R_W(MPU6050_Address, Write);
	MyI2C_ReceiveAck();
	MyI2C_SetRegAddress(RegAddress);
	MyI2C_ReceiveAck();
    while (Count--)
    {
        MyI2C_SendByte(*Data);
        MyI2C_ReceiveAck();
        Data++;
    }
    MyI2C_Stop();
}

//指定地址读 一个字节
uint8_t MPU6050_ReadReg_Single(uint8_t RegAddress)
{
    uint8_t Data;
    MyI2C_Start();
	MyI2C_SetAddress_R_W(MPU6050_Address, Write);
	MyI2C_ReceiveAck();
	MyI2C_SetRegAddress(RegAddress);
	MyI2C_ReceiveAck();
    MyI2C_Start();
	MyI2C_SetAddress_R_W(MPU6050_Address, Read);
	MyI2C_ReceiveAck();
    Data = MyI2C_ReceiveByte();
    MyI2C_SendAck(Stop);
    MyI2C_Stop();
    return Data;
}

//指定地址读 多个字节
void MPU6050_ReadReg_Multiply(uint8_t RegAddress, uint8_t Count)
{
    uint8_t p = 0;
    MyI2C_Start();
	MyI2C_SetAddress_R_W(MPU6050_Address, Write);
	MyI2C_ReceiveAck();
	MyI2C_SetRegAddress(RegAddress);
	MyI2C_ReceiveAck();
    MyI2C_Start();
	MyI2C_SetAddress_R_W(MPU6050_Address, Read);
	MyI2C_ReceiveAck();
    while (Count-- > 1)
    {
        MPU6050_ReceiveData[p] = MyI2C_ReceiveByte();
        MyI2C_SendAck(Continue);
        p ++;
    }
    MPU6050_ReceiveData[p] = MyI2C_ReceiveByte();
    MyI2C_SendAck(Stop);
    MyI2C_Stop();
}

void MPU6050_Init(void)
{
    MyI2C_Init();
	MPU6050_WriteReg_Single(MPU6050_PWR_MGMT_1, 0x01);                  //配置电源管理1,解除睡眠，选择陀螺仪时钟
	MPU6050_WriteReg_Single(MPU6050_PWR_MGMT_1, 0x00);                  //配置电源管理2,6个轴均不待机
	MPU6050_WriteReg_Single(MPU6050_SMPLRT_DIV, 0x09);                  //9分频
	MPU6050_WriteReg_Single(MPU6050_CONFIG, 0x06);                      //无外部同步，最高低通滤波
	MPU6050_WriteReg_Single(MPU6050_GYRO_CONFIG, 0x18);                 //陀螺仪，不自测，最大量程
	MPU6050_WriteReg_Single(MPU6050_ACCEL_CONFIG, 0x18);                //加速度，不自测，最大量程
}

uint8_t MPU6050_GetID(void)
{
    return MPU6050_ReadReg_Single(MPU6050_WHO_AM_I);
}



//依次返回Ax Ay Az 温度 Gx Gy Gz 数据在MPU6050_Stateinfo里面
//注意 xyz的数据分高低位存储
void MPU6050_GetData(void)
{
    uint8_t i;
    MPU6050_ReadReg_Multiply(MPU6050_ACCEL_XOUT_H, 14);
    for (i = 0; i < 7; i ++)
    {
        MPU6050_Stateinfo[i] = (MPU6050_ReceiveData[2 * i] << 8) | MPU6050_ReceiveData[2 * i + 1];     //因为整型提升，所以可以不写强制类型转换
    }
}

